import { Component, OnInit, ViewChild, inject } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { STColumn, STComponent } from '@delon/abc/st';
import { SFSchema } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { SHARED_IMPORTS } from '@shared';
import { lastValueFrom } from 'rxjs';
import { AppValidators } from 'src/app/core/utils/app-validators';
import { BaseService } from 'src/app/core/utils/base.service';
import { CodeConstant } from 'src/app/core/utils/code-constant';

@Component({
  selector: 'app-drug-prdr',
  standalone: true,
  imports: [...SHARED_IMPORTS],
  templateUrl: './prdr.component.html'
})
export class DrugPrdrComponent implements OnInit {
  // 厂商信息
  private drugCompanyInfo: any;
  public url = '/api/dc/drug-prdr';
  // 详细/添加画面显示Flag
  public editVisible = false;
  // 画面title
  public detailTitle = '';
  // 详细画面Form
  public editForm!: FormGroup;
  // 公司类型集合
  public typeList: any[] = [];

  searchSchema: SFSchema = {
    properties: {
      no: {
        type: 'string',
        title: '编号'
      }
    }
  };
  @ViewChild('st') private readonly st!: STComponent;
  public columns!: STColumn[];

  constructor(
    private http: _HttpClient,
    private modal: ModalHelper,
    private fb: FormBuilder,
    private baseService: BaseService
  ) {
    this.CreateForm();
    this.createColumns();
  }

  ngOnInit(): void {}

  /**
   * 创建编辑画面的Form
   */
  CreateForm() {
    this.editForm = this.fb.group({
      id: [],
      // 厂商编码
      prdrCodg: [null, [AppValidators.required('E0001', '编码'), AppValidators.pattern(CodeConstant.REGEXP_EN_NUM, 'E0003', '编码')]],
      // 厂商名称
      prdrName: [null, AppValidators.required('E0001', '名称')],
      // 电话
      tel: [null, [AppValidators.mobile('E0003', '电话')]],
      // 地址
      address: [null],
      // 使用状态
      isValid: []
    });

    this.editForm.get('code')?.disable();
  }

  createColumns() {
    this.columns = [
      { title: '生产厂家名称', index: 'prdrName' },
      { title: '生产厂家编码', index: 'prdrCodg' },
      { title: '拼音码', index: 'pinyincode' },
      { title: '联系人', index: 'coner' },
      { title: '电话', index: 'tel' },
      { title: '审核人编码', index: 'chkerCodg' },
      { title: '审核人名称', index: 'chkerName' },
      { title: '审核时间', index: 'chkTime' },
      {
        title: '',
        buttons: [
          { text: '详细', click: (item: any) => this.drugCompanyDetail(item) },
          { text: '删除', click: (item: any) => this.drugCompanyDelete(item) }
        ]
      }
    ];
  }

  add(): void {
    // this.modal
    //   .createStatic(FormEditComponent, { i: { id: 0 } })
    //   .subscribe(() => this.st.reload());
  }

  /**
   * 新建按钮点击事件
   */
  createdrugCompany() {
    this.resetForm();
    this.detailTitle = '新增厂商';
    this.editVisible = true;
  }

  /**
   * 重置Form
   */
  resetForm() {
    this.editForm.reset();
    this.drugCompanyInfo = null;
  }

  /**
   * 厂商详细
   */
  async drugCompanyDetail(data: any) {
    this.resetForm();
    this.detailTitle = '编辑厂商';
    var result = await lastValueFrom(this.http.get(`/api/drug/drug/${data.id}/drug-company`));
    if (result) {
      this.drugCompanyInfo = result;
      this.editForm.patchValue(result);
      this.editVisible = true;
    }
  }

  /**
   * 删除厂商
   */
  async drugCompanyDelete(data: any) {
    this.baseService.showConfirm({
      message: this.baseService.getMessage('C0001'),
      okCallback: async () => {
        var result = await lastValueFrom(this.http.delete(`/api/drug/drug/${data.id}/drug-company`));
        this.st.reload();
      }
    });
  }

  /**
   * 保存药品目录
   */
  async save() {
    if (this.baseService.hasError(this.editForm)) {
      return;
    }

    const formValue = this.editForm.getRawValue();
    // 更新的处理
    if (this.drugCompanyInfo && this.drugCompanyInfo.id) {
      const result = await lastValueFrom(
        this.http.put(`${this.url}/${this.drugCompanyInfo.id}`, Object.assign(this.drugCompanyInfo, formValue))
      );
      if (result) {
        this.st.reload();
        this.editVisible = false;
      }
    } else {
      const { id, ...param } = formValue;
      // 新增处理
      const result = await lastValueFrom(this.http.post(this.url, param));
      if (result) {
        this.st.reload();
        this.editVisible = false;
      }
    }
  }

  /**
   * 关闭详细画面
   */
  close(): void {
    this.editVisible = false;
  }
}
